#encoding:utf8

'''
Simple RTX wrapper
'''

import time
import win32con
import win32api
import win32gui
import win32com.client
from lib import clipboard


###########################################################################
def getstatus(user):
    '''
    Get rtx user status:
    0---> offline
    1---> online
    2---> away
    '''
    rtxapi      = win32com.client.Dispatch('RTXClient.RTXAPI')
    presence    = rtxapi.GetObject('Presence')
    CMD_GetState= 1
    ret         = presence.Call(CMD_GetState, user)
    status      = ret.Value('Status')
    return status


def getinfo(user):
    '''
    get a user info

        buddy.Name
        buddy.Gender
        buddy.Account
        buddy.Telephone
        buddy.Email
        buddy.Mobile
    '''
    rtxapi      = win32com.client.Dispatch('RTXClient.RTXAPI')
    kernal      = rtxapi.GetObject("KernalRoot")
    buddyManager= kernal.RTXBuddyManager
    buddy       = buddyManager.Buddy(user)
        
    #print(buddy.Name, buddy.Gender)
    return buddy


###########################################################################
def sendmessage(receivers, text= None):
    '''
    Send message to receivers
    '''
    def combineKey(control, letter):
        '''
        combine key
        '''
        win32api.keybd_event(control, 0, 0, 0)
        win32api.keybd_event(ord(letter), 0, 0, 0)
        win32api.keybd_event(ord(letter), 0, win32con.KEYEVENTF_KEYUP, 0)
        win32api.keybd_event(control, 0, win32con.KEYEVENTF_KEYUP, 0)
    
    def enumWindowCallBack(hwnd, preTitle):
        title   = win32gui.GetWindowText(hwnd)
        # print 'title= ', title, type(title), 'preTitle= ', preTitle, type(preTitle)
        if title.endswith('- RTX conversation') and title.startswith(preTitle):
            #print(title)
            win32gui.SetForegroundWindow(hwnd)
            enumWindowCallBack.isFind   = True
            return False

    # open the message window
    rtxapi      = win32com.client.Dispatch('RTXClient.RTXAPI')
    im          = rtxapi.GetObject('RTXPlugin.IM')
    CMD_SendIM  = 1
    im.Call(CMD_SendIM, receivers)
    
    if text:
        # fetch receivers name 
        receiverList    = sorted(receivers.split(';'))
        nameList        = [getinfo(user).Name for user in receiverList]
        nameInTitle     = '; '.join(nameList)
        preTitle        = nameInTitle if len(nameInTitle) < 8 else nameInTitle[:8]

        # sleep util find the rtx chat oindow or reach the maxSleepTime
        timeCounter     = 0
        maxSleepTime    = 3
        enumWindowCallBack.isFind   = False
        while timeCounter < maxSleepTime:
            try:
                # 调用win32gui函数的时候，应该使用gbk编码的字符串
                if isinstance(preTitle, unicode):
                    preTitle    = preTitle.encode('gbk')
                win32gui.EnumWindows(enumWindowCallBack, preTitle)
            except:
                if enumWindowCallBack.isFind:
                    clipboard.text  = text
                    
                    # send message and close the window
                    combineKey(win32con.VK_CONTROL, 'V')    # ctrl + v --> paste
                    combineKey(win32con.VK_MENU, 'S')       # alt + s --> send
                    combineKey(win32con.VK_MENU, 'C')       # alt + c --> close
                    break

                step    = 0.2
                time.sleep(step)
                timeCounter+= step
                #print('timeCounter= ', timeCounter)

###########################################################################

if __name__=='__main__':
    userid      = 1317
    user        = u'hanwei'
    receivers   = u'tuqiang;hanwei'
    text        = u'大家好'

    #print(getstatus(user))
    #print(getinfo(user))
    sendmessage(receivers, text)


